<template>
	<base-page title="添加核销商品" backgroundColor="white">
		<view class="mx-16">
			<view class="mt-16">
				<view class="mb-8"><text class="text-bold">商品名称</text></view>
				<view class="uni-bg-white radius-8 p-12">
					<textarea
						class="text-color-regular fs-14"
						:maxlength="30"
						v-model="formData.goodsName"
						placeholder-style="color:#A5A7A9;"
						placeholder="*请输入商品名称（最多30字）"
						:auto-height="true"
					/>
				</view>
			</view>
			<view class="flex flex-col mt-16">
				<view>
					<text class="text-bold">商品图片</text><text class="text-color-hint">（建议图片比例1:1）</text>
				</view>
				<drag-image v-model="files" keyName="url" :isIntegral="true" :imageWidth="180" :padding="20" :borderRadius="12" :addImage="toChooseFile" :delImage="delImage"></drag-image>
			</view>
			<view class="flex justify-between item-center pt-16 pb-12 border-top">
				<view class="flex-col">
					<text class="text-bold">商品结算价格</text>
					<text class="fs-10 text-color-hint whitespace-nowrap">商品核销后，策划人需要补贴给商户的金额</text>
				</view>
				<view class="flex item-center">
					<input
						v-model="formData.amount"
						class="text-color-regular fs-14 text-right"
						type="digit"
						:maxlength="8"
						placeholder="请输入"
						placeholder-class="text-color-hint"
					/>
					<text class="fs-14 c3 ml-4">元</text>
				</view>
			</view>
			<view class="flex justify-between item-center pt-16 pb-12 border-top">
				<view class="flex-col">
					<text class="text-bold">上架数量</text>
				</view>
				<view class="flex item-center">
					<input
						v-model="formData.totalNum"
						class="text-color-regular fs-14 text-right"
						type="number"
						placeholder="请输入"
						placeholder-class="text-color-hint"
					/>
					<text class="fs-14 c3 ml-4">件</text>
				</view>
			</view>
			<view class="flex justify-between item-center pt-16 pb-12 border-top">
				<view class="flex-col">
					<text class="text-bold">使用期限</text>
				</view>
				<view class="flex item-center">
					<input
						v-model="formData.dayLimit"
						class="text-color-regular fs-14 text-right"
						type="number"
						placeholder="请输入"
						placeholder-class="text-color-hint"
					/>
					<text class="fs-14 c3 ml-4">天</text>
				</view>
			</view>
			<view class="flex justify-between item-center pt-16 pb-12 border-top">
				<view class="flex-col">
					<text class="text-bold">兑换需</text>
				</view>
				<view class="flex item-center">
					<input
						v-model="formData.requiredPoints"
						class="text-color-regular fs-14 text-right"
						type="number"
						placeholder="请输入"
						placeholder-class="text-color-hint"
					/>
					<text class="fs-14 c3 ml-4">积分</text>
				</view>
			</view>
			<view class="flex justify-between item-center pt-16 pb-12 border-top">
				<view class="flex-col">
					<text class="text-bold">上架时间</text>
				</view>
				<view class="flex item-center">
					<uni-datetime-picker v-model="formData.effectiveTime" isDefaultTime>
						<view class="flex justify-end item-center">
							<text class="text-color-hint">{{ formData.effectiveTime ? formData.effectiveTime : '未设置' }}</text>
							<image class="w-16 h-17 ml-4" src="@/static/svg/icon-arrow-right.svg"></image>
						</view>
					</uni-datetime-picker>
				</view>
			</view>
			<view class="flex justify-between item-center pt-16 pb-12 border-top">
				<view class="flex-col">
					<text class="text-bold">适用商户</text>
				</view>
				<view class="flex item-center" @click="open">
					<text class="text-color-hint">{{ formData.merchantIds && formData.merchantIds.length ? '已设置' : '去设置' }}</text>
					<image class="w-16 h-17 ml-4" src="@/static/svg/icon-arrow-right.svg"></image>
				</view>
			</view>
			<view class="mt-16">
				<view class="mb-8"><text class="text-bold">商品详情</text></view>
				<view class="uni-bg-white radius-8 p-12">
					<rich-editor ref="richEditor" v-model="formData.details" :uploadFilePurpose="2" placeholder="*请输入活动内容"></rich-editor>
				</view>
			</view>
		</view>
		<template #footer>
			<view class="m-12 flex">
				<button class="flex-1 flex center radius-8 h-46 fs-16 uni-bg-white text-color-hint mr-12" style="border:1px solid rgba(51, 51, 51, 0.60);" @click="goBack">取消</button>
				<button class="flex-1 flex center radius-8 h-46 fs-16 bg-primary text-white" @click="submit">确认</button>
			</view>
		</template>
		<uni-popup ref="popup" type="bottom">
			<view class="uni-bg-white fs-14">
				<view class="flex justify-between item-center h-40" style="border-bottom:1px solid #f5f5f5;">
					<text class="text-color-hint p-10" @click="close">收起</text>
					<text class="color-secondary-info p-10" @click="onConfirm">确定</text>
				</view>
				<view class="flex item-center px-16" @click="ChangeSelOffList()">
					<image src="@/static/svg/radio-blue-selected.svg" mode="" class="w-16 h-16 mr-4" v-if="selectList.length && selectList.length == merchantList.length"></image>
					<image src="@/static/svg/radio-default.svg" mode="" class="w-16 h-16 mr-4" v-else></image>
					全选
				</view>
				<view class="p-16" style="max-height: 50vh;overflow: auto;">
					<view class="flex mb-28 item-center" v-for="(item,index) in merchantList" :key="index">
						<view class="flex">
							<view class="flex item-center" @click="check(item)">
								<image v-if="selectList.includes(item.id)" class="w-16 h-16" src="@/static/svg/activity/icon-radio-check-blue.svg"></image>
								<image v-else class="w-16 h-16" src="@/static/svg/activity/icon-radio-default.svg"></image>
								<image class="goods-img" :src="item.avatar"></image>
							</view>
						</view>
						<view class="mb-6">
							<view class="mb-4"><text class="goods-name">{{item.merchantShortName}}</text></view>
						</view>
					</view>
				</view>
			</view>
		</uni-popup>
	</base-page>
</template>

<script setup name="AddGoods">
	import { onLoad, onShow } from '@dcloudio/uni-app'
	import {
		computed,
		onMounted,
		ref,
		unref,
		toRaw,
	} from 'vue'
	import DragImage from '../components/drag-image/drag-image.vue'
	import RichEditor from '@/pagesJ/integralSetting/components/rich-editor/rich-editor.vue'
	import { productDetailApi, saveGoodsApi } from '@/pagesJ/api/index.js'
	import { getRelationMerchantApi } from '@/api/activity.js'
	import { isVideoFile } from '@/utils/index.js'
	import { uploadFileApi } from '@/api/common.js'
	import dayjs from 'dayjs'
	
	const formData = ref({
		effectiveTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
		merchantIds: [],
		details: []
	})
	const popup = ref(null)
	const selectList = ref([])
	const merchantList = ref([])
	const getRelationMerchant = async () => {
		let result = await getRelationMerchantApi({pageNum: 1,pageSize: 100})
		if(result){
			merchantList.value = result.list || []
		}
	}
	const open = () => {
		selectList.value = JSON.parse(JSON.stringify(formData.value.merchantIds))
		popup.value && popup.value.open()
	}
	
	const close = () => {
		popup.value && popup.value.close()
	}
	const onConfirm = () => {
		formData.value.merchantIds = selectList.value
		close()
	}
	const ChangeSelOffList = () => {
		if(merchantList.value.length != selectList.value.length) {
			selectList.value = merchantList.value.map(item => {
				return item.id
			})
		}else {
			selectList.value = []
		}
	}
	const check = (item) => {
		const index = selectList.value.findIndex(it => it === item.id)
		if (index !== -1) {
			selectList.value.splice(index, 1)
		}else{
			selectList.value.push(item.id)
		}
	}
	
	const files = ref([])
	const MAX_FILE_LENGTH = 6
	const toChooseFile = () => {
		uni.chooseMedia({
			count: MAX_FILE_LENGTH - files.value.length, // 最多一个视频，视频+图片不能超过6张
			mediaType: ['image'], // mix 可同时选择图片和视频
			// maxDuration: 30, // 拍摄视频最长拍摄时间，单位秒。时间范围为 3s 至 30s 之间
			sourceType: ['album', 'camera'],
			camera: 'back',
			success: ({ tempFiles }) => {
				if (tempFiles && tempFiles.length) {
					for (var i = 0; i < tempFiles.length; i++) {
						const file = tempFiles[i]
						console.log('选择文件', i, file, files.value, tempFiles)
						if (files.value.length > MAX_FILE_LENGTH) {
							return
						}
						if (file.fileType === 'video') {
							const hasAdd = files.value.some(f => f.fileType === 'video')
							if (hasAdd) {
								uni.showToast({
									icon: 'none',
									title: '至多只能上传1个视频'
								})
							} else {
								uploadFile(file, files)
							}
						} else {
							uploadFile(file, files)
						}
					}
				}
			}
		})
	}
	
	const uploadFile = (file, files) => {
		uni.showLoading()
		uploadFileApi(2, {
			name: 'file',
			filePath: file.tempFilePath
		}).then(res => {
			uni.hideLoading()
			if (res.code === 200) {
				files.value.push(file)
				file.url = res.data
			} else {
				uni.showToast({
					icon: 'none',
					title: res.message
				})
			}
		})
	}
	
	const deleteFile = (index) => {
		files.value.splice(index, 1)
	}
	
	const delImage = (done) => {
		done()
	}

	const goBack = () => uni.navigateBack()
		
	const submit = () => {
		if (!formData.value.goodsName) {
			uni.showToast({
				icon: 'none',
				title: '请填写商品名称'
			})
			return
		}
		formData.value.goodsImages = files.value.map(f => f.url) || []
		if (!formData.value.goodsImages.length) {
			uni.showToast({
				icon: 'none',
				title: '请填写上传商品图片'
			})
			return
		}
		if (!formData.value.amount && formData.value.amount != 0) {
			uni.showToast({
				icon: 'none',
				title: '请填写商品结算价格'
			})
			return
		}
		if (!formData.value.totalNum) {
			uni.showToast({
				icon: 'none',
				title: '请填写上架数量'
			})
			return
		}
		if (!formData.value.dayLimit) {
			uni.showToast({
				icon: 'none',
				title: '请填写使用期限'
			})
			return
		}
		if (!formData.value.requiredPoints) {
			uni.showToast({
				icon: 'none',
				title: '请填写兑换积分'
			})
			return
		}
		if (!formData.value.effectiveTime) {
			uni.showToast({
				icon: 'none',
				title: '请填写上架时间'
			})
			return
		}
		if (!(formData.value.details && formData.value.details.length > 0)) {
			uni.showToast({
				icon: 'none',
				title: '请填写商品详情'
			})
			return
		} else {
			formData.value.details = formData.value.details.map((it, i) => ({
				...it,
				sort: i + 1
			}))
		}
		saveGoodsApi(formData.value).then(res => {
			uni.showToast({
				icon: 'none',
				title: '保存成功'
			})
			setTimeout(()=>{
				goBack()
			}, 1000)
		})
	}
	
	onLoad((query) => {
		if(query && query.id){
			productDetailApi({id: query.id}).then(res => {
				formData.value = res
				files.value = res.goodsImages.map(item => {
					return {url: item, fileType: isVideoFile(item) ? 'video' : 'image'}
				})
				if (typeof formData.value.details === 'string') {
					formData.value.details = formData.value.details && JSON.parse(formData.value.details) || []
				}
			})
		}
	})
	
	onMounted(() => {
		getRelationMerchant()
	})
</script>
<style scoped lang="scss">
	.border-top{
		border-top: 1px solid #F5F5F5;
	}
	.goods-img {
		width: 48px;
		height: 48px;
		border-radius: 12px;
		margin-right: 12px;
		margin-left: 16px;
	}
	.goods-name {
		color: #333;
		font-family: PingFang SC;
		font-size: 14px;
		font-style: normal;
		font-weight: 600;
		line-height: normal;
	}
</style>